package com.dm.cloud.images.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ssh.JschUtil;
import cn.hutool.extra.ssh.Sftp;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.Info;
import com.dm.cloud.images.mode.NodeInfo;
import com.dm.cloud.images.util.DockerUtil;
import com.dm.cloud.tkmybatis.service.BaseMapper;
import com.dm.cloud.images.mapper.ImagesEndpointMapper;
import com.dm.cloud.images.service.ImagesEndpointService;
import com.dm.cloud.images.common.po.ImagesEndpoint;
import com.dm.cloud.core.exception.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;

/**
   * @author hcx
   * @type ImagesEndpointServiceImpl.java
   * @desc ImagesEndpoint serviceImpl
   */
@Service

@Transactional

public class ImagesEndpointServiceImpl implements ImagesEndpointService {


    @Autowired
    private ImagesEndpointMapper imagesEndpointMapper;


    @Override
    public BaseMapper getMapper() {
        return imagesEndpointMapper;
    }

    public void processBeforeOperation(ImagesEndpoint entity, BaseOperationEnum operationEnum) throws CustomException {
        if(operationEnum.equals(BaseOperationEnum.INSERT)){
            checkParam(entity);
        }else if(operationEnum.equals(BaseOperationEnum.UPDATE)){
            checkParam(entity);
        }

    }

    public void processAfterOperation(ImagesEndpoint entity, BaseOperationEnum operationEnum) throws CustomException {

    }

    private void checkParam(ImagesEndpoint entity){
        if(StrUtil.isEmpty(entity.getHost())){
            throw new CustomException("节点IP不能为空!");
        }else if(StrUtil.isEmpty(entity.getName())){
            throw new CustomException("节点名称不能为空!");
        }else if(StrUtil.isEmpty(entity.getDockerShard())){
            throw new CustomException("节点节点共享目录不能为空!");
        }else if(entity.getPort()==null){
            throw new CustomException("节点SSH端口不能为!");
        }else if(entity.getDockerPort()==null){
            throw new CustomException("节点dockerApi端口不能为空!");
        }
        //验证docker api
        DockerClient dockerClient=null;
        try {
            dockerClient = DockerUtil.get(entity.getHost(), entity.getDockerPort());
            if(!DockerUtil.pingNode(dockerClient)){
                throw new CustomException("docker api 连接失败，请检查是否开启");
            }
        }catch (Exception e){
            if(e instanceof CustomException){
               throw e;
            }
            throw new CustomException("docker api 连接失败，请检查是否开启");
        }finally {
            try {
                dockerClient.close();
            } catch (IOException e) {
//                e.printStackTrace();
            }
        }
        //验证ssh
        Sftp sftp= null;
        try {
            sftp=getEndpointConn(entity);
            //验证共享目录
            if(!sftp.isDir(entity.getDockerShard())){
                throw new CustomException("共享目录不存在");
            }
        }finally {
            try {
                sftp.close();
            }catch (Exception e){}
        }

//        //验证目录和ssh
//        SftpClient sftpClient=new SftpClient(entity.getHost(),entity.getPort(),entity.getUname(),entity.getUpwd());
//        try {
//
//
//
//        }catch (Exception e){
//            e.printStackTrace();
//        }finally {
//            sftpClient.close();
//        }
    }

//    /**
//     * 验证共享目录
//     * @param sftpClient
//     * @param entity
//     */
//    private void testDockerShard(SftpClient sftpClient,ImagesEndpoint entity){
//
//        //先检查共享目录是否存在，不存在则创建
//        if(!sftpClient.isDir(entity.getDockerShard())){
//
//        }
//
//    }

    /**
     * 获取连接
     * @return
     */
    public Sftp getEndpointConn(ImagesEndpoint entity){
        try {
            Sftp sftp= JschUtil.createSftp(entity.getHost(),entity.getPort(),entity.getUname(),entity.getUpwd());
            return sftp;
        }catch (Exception e){
            e.printStackTrace();
            throw new CustomException("ssh连接失败!");
        }
    }


    @Override
    public ImagesEndpoint findActiveLimit1() {
        return imagesEndpointMapper.findActiveLimit1();
    }

    @Override
    public DockerClient getClientByNodeId(String nodeId) {
        ImagesEndpoint endPointPo = getById(nodeId);
        if(endPointPo==null || ObjectUtil.isEmpty(endPointPo)){
            throw new CustomException("节点不存在！");
        }
        DockerClient dockerClient = DockerUtil.get(endPointPo.getHost(), endPointPo.getDockerPort());
        return dockerClient;
    }

    @Override
    public NodeInfo nodeInfo(String nodeId) {
        ImagesEndpoint endPointPo = getById(nodeId);
        DockerClient dockerClient = null;
        try {
            dockerClient = DockerUtil.get(endPointPo.getHost(), endPointPo.getDockerPort());
            Info info = DockerUtil.nodeInfo(dockerClient);
            NodeInfo nodeInfo=NodeInfo.buildByInfo(info,nodeId,endPointPo.getName(),endPointPo.getHost());
            return nodeInfo;
        }catch (Exception e){
            throw new CustomException("获取节点状态失败!");
        }finally {
            try {
                dockerClient.close();
            } catch (IOException e) {}
        }
    }

    @Override
    public List<ImagesEndpoint> findByAppCode(String appCode) {
        return imagesEndpointMapper.findByAppCode(appCode);
    }
}
